#!/bin/bash
# makefusiondebs script for easy compiling and building deb packages for
# Compiz Fusion (and related tools) GIT
#
# (c) 2008 Some-Guy - Under GPLv2
# based on makefusiondebs
############################################################################
# (c) 2006-2007 Treviño - Released under GPLv2 Terms
# This script is based on those I built few months ago for beryl git and svn
############################################################################
#
#  USAGE
#  You should simply run this script to create and your fusion git
#  tree and package it, but there are also some "advanced" tasks:
#
#    ./makefusiondebs                 performs all the tasks (sync and package)
#    ./makefusiondebs update          just sync the local data to remote git
#    ./makefusiondebs build           try to build the needed items
#    ./makefusiondebs <item>          build only the <item> (if needed)
#    ./makefusiondebs rebuild <item>  force a rebuild of the <item>
#    ./makefusiondebs repack <item>   force a repack of the <item>
#
#   You can define some personal settings, editing the file called by
#   the $settingfile variable (see the code below)
#
#   To change the content of a package (or applying patch) you can add
#   some bash script files called "pkgxtra.sh" on each <item> dir to
#   perform extra tasks after that each package has been compiled.
#   However on the best way to change the code of a package is that of
#   applying patches directly to it using the debian patches as it's
#   done in some debian dirs used in compiz-fusion.
#   You can use a personal (user) debian dir for this as show below
#
#   To Package an <item> file not included yet on the $DISTRODIR or to
#   override the way used for packaging, you can add an "<item>/debian"
#   tree to your $DISTRODIR_USER folder; it will be used instead of
#   the default one (if present)
############################################################################

OPTIONS="bfd-options"
OPTIONS_EXTRA="bfd-extra"
OPTIONS_EXTRA_USER="$OPTIONS_EXTRA-user"

#############
## end config
#############

## THOSE ARE STANDARD OPTIONS - DON'T EDIT THEM HERE - USE THE SETTING FILE ##
PACKAGER="Trevi - 3v1n0"
PACKAGER_EMAIL="trevi55@gmail.com"
PACKAGE_SUFFIX="3v1ubuntu"

DEBDIR="debs"
DEBOLDDIR="debs-old"
CHANGEDIR="changelogs"
DISTRODIR="compiz-fusion-debian"
DISTRODIR_USER="compiz-fusion-debian-user"
GITURL="git://anongit.compiz-fusion.org"
GITWEB="http://gitweb.opencompositing.org"
GITBLACKLIST="\/logs\|\/makefile$\|\/i18n$"
GITWHITELIST="^fusion/\|^compiz$\|3v1n0/compiz-wrapper$\|3v1n0/compiz-fusion-debian$"
GITEXTRA="\/plugins\/"
EXTRAITEMSUPPORT="true"
PRIOPKGS="compiz bcop libcompizconfig plugins-main"
AUTOUPDATE="true"
INCLUDEDEBUG="true"

if [ -f "$OPTIONS" ]; then
	. $OPTIONS
fi

MY_ARGS="$*"
DATA_DIR="fusion"
EXTRA_DIR="$datadir/extra-items"

if [ "$EXTRAITEMSUPPORT" = "true" ]; then
	if [ -f "$OPTIONS_EXTRA" ]; then
		. "$OPTIONS_EXTRA"
	fi
	if [ -f "$OPTIONS_EXTRA_USER" ]; then
		. "$OPTIONS_EXTRA_USER"
	fi
fi

# == prefix
DEFPREFIX="/usr"
MYPREFIX=${PREFIX:-$DEFPREFIX}

# == command to build compiz
autogenpkg_cmd="./autogen.sh --prefix=$MYPREFIX"
buildpkg_cmd="fakeroot dpkg-buildpackage -b -us -uc"
repkg_cmd="fakeroot ./debian/rules binary"
patch_cmd="fakeroot ./debian/rules apply-patches"
unpatch_cmd="fakeroot ./debian/rules reverse-patches"

gitweb_items="$(wget -q -O - "$GITWEB/?a=project_index")"

git_items="$(echo "$gitweb_items"|cut -d' ' -f1|grep -v "$GITBLACKLIST\|$GITEXTRA"|grep "$GITWHITELIST")"

if [ -n "$GITEXTRA" ]; then
	gitextra_items="$(echo "$gitweb_items"|cut -d' ' -f1|grep -v "$GITBLACKLIST"|grep "$GITEXTRA")"
fi

## TODO
# Extra packages support
# Reanalyze the git update [quite done...]
# Repack on debian directory changed (only if git)
# Add CFLAGS, LDFLAGS support
# CHECK WHEN building/rebuilding extra

function git_commit {
	#git-log|grep -m1 commit|cut -d' ' -f2
	if [ -d ".git" ]; then
		git-rev-parse HEAD
	else
		unset githeads
		for subdir in *; do
			if [ -d "$subdir/.git" ]; then
				cd $subdir
				githeads="$githeads $(git-rev-parse HEAD)"
				cd ..
			fi
		done
		if [ -n "$githeads" ]; then
			echo "$githeads"
		fi
	fi
}

function git_commit_date {
	if git-log &> /dev/null; then
		if [ -d ".git" ]; then
			date -d "$(expr "$(git-log|grep "Date" -m1)" : "Date:[ ]\+\(.*\)[+-]\{1\}[0-9]\{4\}")" +"%Y%m%d"
		else
			gitdate=0
			for subdir in *; do
				if [ -d "$subdir/.git" ]; then
					cd $subdir
					tmpdate=$(date -d "$(expr "$(git-log|grep "Date" -m1)" : "Date:[ ]\+\(.*\)[+-]\{1\}[0-9]\{4\}")" +"%s")
					if [ $tmpdate -gt $gitdate ]; then
						gitdate=$tmpdate
					fi
					cd ..
				fi
			done
			date -d "1970-01-01 $gitdate sec GMT" +"%Y%m%d"
		fi
	else
		echo "0"
	fi
}

# == add an ignore rule to git
function git_ignore_add {
	if [ -d ./.git ]; then
		ignorefile=".gitignore"
		touch "$ignorefile"
		for ignore in "$ignorefile" $@; do
			if !(grep -qw "$ignore" "$ignorefile"); then
				echo "$ignore" >> "$ignorefile"
			fi
		done
	fi
}

# == pull in updates, then check if fatalities occured
function git_pull_check {
	git_pull="$(LC_ALL=en_US git-pull &> /dev/stdout)"
	echo "$git_pull"
	if (echo "$git_pull" | grep -qi "^fatal:"); then
		return 1
	else
		return 0
	fi
}

# == the packages failed to build, ask the user what to do
function askuser {
	# == prompt
	read -p " [Y/n]: " -n1 continue
	# == decide
	if (echo "$continue" | grep -qi "y"); then
		echo ''
		return 0
	else
		echo ''
		return 1
	fi
}

function errorcontrol {
	item="$1"
	if [ -z "$(echo $commandline | grep "batch")" ]; then
		echo -e "\nProblems occurred while building $item packages... Continue Building?"
		if ! (askuser); then
			echo -e "$report\n";
			exit 2
		fi
	else
		echo -e "\nProblems occurred while building $item packages. Skipping as requested..."
	fi
}

# == check for an app
function checksw {
	BIN="$1"
	PACKAGE="$2"
	# == if package name isn't provided, assume that package name is binary name
	[ -n $PACKAGE ] || PACKAGE=BIN
	# == check for existance
	if [ -z "$(which $BIN)" ]; then
		echo -e "\nYou must install the '$PACKAGE' package in order to use needed git tools\n"
		exit 2
	fi
}

function git_sync {
	if [ -n "$1" ]; then
		git_url="$1"
	fi
	if [ -n "$2" ]; then
		git_item="$2"
	fi
	if [ -n "$3" ]; then
		git_base_dir="$3"
	fi
	git_item_name="$(basename $git_item)"
	#git_item_dir="$(dirname $git_item)"
	git_item_dir="$git_base_dir/$git_item_name"
	#mkdir -p $git_item_dir;
	if (find "$datadir" -type d -name "$git_item_name" | grep -wqv "$git_base_dir\|\.git"); then
		if [ -d "$git_item_dir" ]; then
			echo -e "\n\033[4mRemoving obsolete '$git_item_name' directory...\033[0m"
			rm -rf $git_item_dir
		fi
		return 0;
	fi
	if [ ! -d "$git_item_dir/.git" ]; then
		echo -e "\n\033[4mNo $git_item_name git folder found! Downloading...\033[0m"
		if (cd "$git_base_dir" && ! git-clone $git_url/$git_item $git_item_name); then
			echo "There are problems retrieving git data for $git_item_name. Skipping..."
			#exit 2;
		fi
		echo ""
	elif [ -d "$git_item_dir" ]; then
		if (cd "$git_item_dir" && ! git-log &> /dev/null); then
			echo "The $git_item_name git directory isn't here, please remove the '$git_item_dir' dir and run again this script."
			echo "Would you like this script make this (all your '$git_item_dir' data will be removed)?"
			if (askuser); then
				rm -rf "$git_item_dir"
				if (cd "$git_base_dir" && ! git-clone $git_url/$git_item $git_item_name); then
					echo "There are problems retriving git data for $git_item_name. Skipping..."
					#exit 2;
				fi
			else
				exit 2;
			fi
		else
			if [ -z "$(echo $commandline | grep -wE "batch|noupdate|build")" ]; then
				echo -e "\n\033[4mUpdating the $git_item_name package...\033[0m"
				if [ -d "$git_item_dir/.pc" ]; then
# 					if [ ! -d "$git_item_dir/debian" ]; then
# 						if [ -d "$DISTRODIR_USER/$git_item_name/debian" ]; then
# 							ln -sf "../$DISTRODIR_USER/$git_item_name/debian" \
# 								"$git_item_dir"
# 						else
# 							ln -sf "../$DISTRODIR/$git_item_name/debian" \
# 								"$git_item_dir"
# 						fi
# 					fi
# 					(cd "$git_item_dir" && $unpatch_cmd)
					rm -rf "$git_item_dir/.pc"
					rm -rf "$git_item_dir/debian"
				fi
				(cd "$git_item_dir" && git-diff-files -p | patch -Rp1 2> /dev/null);
				if ! (cd "$git_item_dir" && git_pull_check); then
					echo "Cleaning the git repository..."
					(cd "$git_item_dir" && git-clean -d -q)
					if ! (cd "$git_item_dir" && git_pull_check); then
						echo "I can't fix the $git_item repository, try to remove the '$git_item_dir' directory and run this script again"
						report="$report\n\033[4mGIT PULL FAILED for $git_item\033[0m"
						sleep 3
					fi
				fi
				
			fi
		fi
	else
		echo "There are some errors with build directories, please report this to the Author"
		exit 2
	fi
}

function git_items_check {
	git_check_type="$1"
	git_base_dir="$2"
	shift 2
	git_items=$*
	git_url=$GITURL
	for git_item in $git_items; do
		git_sync $git_url $git_item $git_base_dir
	done
	unset git_items
}

mkdir -p "$datadir" "$extradir"

# == check for git
checksw "git-clone" "git-core"

# == check for root powers
if [ "$(whoami)" != "root" ]; then
	checksw "sudo"
fi

# == check for patch, fakeroot, dpkg-buildpackage, and dh_builddeb 
checksw "patch"
checksw "fakeroot"
checksw "dpkg-buildpackage" "dpkg-dev"
checksw "dh_builddeb" "debhelper"

# == check to see if list is blank and 'noupdate parameter is provided'
if ( [ -z "$git_items" ] && [ -z "$(echo $commandline | grep -w "noupdate")" ] ); then
	echo "There are problems while retrieving the fusion items list."
	echo "Would you like to force the upgrade trying to fetch updates from all the git folders available in $datadir/ ?"
	askuser || (echo "Exiting..."; exit 2)
	for datasubdir in fusion/*; do
		if [ -d "$datasubdir/.git" ]; then
			git_items="$git_items $datasubdir";
		fi;
	done
fi

# == see if the autoupdate option is disable
if [ "$AUTOUPDATE" != "true" ]; then
	echo -e "\nAutoupdate feature for makefusiondebs disabled"
# == if it is enabled, make git ignore our folders and config
elif ( [ -d ".git" ] && git-log &> /dev/null ); then
	git_ignore_add "$OPTIONS_EXTRA_USER" "$OPTIONS_EXTRA_USER" "$OPTIONS" "$datadir/" "$DEBDIR/" "$DEBOLDDIR/" "$CHANGEDIR/"
	echo -e "\n\033[4mUpdating $0 script...\033[0m"
	oldcommit="$(git_commit)"
	# == update the script, if it failed, ask
	if ! git_pull_check; then
		report="$report\nSCRIPT AUTOUPDATE FAILED"
		echo "SCRIPT AUTOUPDATE FAILED"
		echo "Would you like continue anyway?"
		if (askuser); then
			echo "Ok, continuing as requested..."
			sleep 1
		else
			exit 2
		fi
	fi
	# if the current commitis different from the old one, reload
	if [ "$(git_commit)" != "$oldcommit" ]; then
		echo -e "\nThe script has been updated, reloading it..."
		sleep 2 && echo "" && $0 $commandline
		exit 0
	fi
fi

# == if the root powers are unavailable, ask to store the sudo password
if [ "$(whoami)" != "root" ] && (echo "$commandline" | grep -vwq "update\|pull"); then
	echo -e "\nThis tool could need the 'sudo' password to install some packages it builds, to avoid the script to stop itself to ask the password, you could define it here. It will be saved and used ONLY to install packages (as you can see from the code).\nWould you like to enter it now?"
	if (askuser); then
		count=0
		sudopwdset="false"
		while [ "$sudopwdset" != "true" ] && [ $count -lt 3 ]; do
			read -s -p "Password:" sudopwd
			echo ''
			sudo -k
			count=$(($count+1))
			if (echo $sudopwd | sudo -S echo -n "" 2> /dev/null); then
				sudopwdset="true"
			fi
		done
		unset count
		if [ "$sudopwdset" = "false" ]; then
			echo -e "\nThe password you provided seems to be wrong, so it will be re-asked when needed"
			sudo -k
			sleep 2
		fi
	fi
fi

git_items_check "main" "$datadir" $git_items

if [ "$EXTRAITEMSUPPORT" = "true" ]; then
	git_items_check "extra" "$extradir" $gitextra_items
	extra_items_do 2> /dev/null
	extra_user_items_do 2> /dev/null
fi

for blackdir in $datadir/*; do
	if [ -d "$blackdir" ] && (echo "$blackdir" | grep -q "$GITBLACKLIST"); then
		rm -rf $blackdir
	fi
done

if [ -n "$(echo $commandline | grep -wE "update|pull")" ]; then
	exit 0;
fi

cd "$datadir"

if [ -f "./VERSION" ]; then
	. "./VERSION"
	base_ver="$VERSION"
	VERSION=""
else
	base_ver=0
fi

function abi_version {
	# Nedded for ABIVERSION check, firstly check if there are functions that returns ABIVERSION in
	# each *.c*/*.h file and saves it to .abi-done, if found it checks if it is equal to the one
	# stored in compiz.h include file; if it is different (lower), then rebuild the package and
	# then store the actual abiversion in .abi-done :)
	file="$1"
	if [ -z "$file" ]; then
		file="../compiz/include/compiz-core.h"
		#file="/usr/include/compiz/compiz-core.h"
	fi
	expr "$(cat "$file")" : ".*#define[ \t]\+CORE_ABIVERSION[ \t]\+\([0-9]\{8\}\).*"
}

function installpackages {
	wait
	echo -e "\a"
	if [ "$sudopwdset" = "true" ]; then
		if (echo "$sudopwd" | sudo -S dpkg -i $* && wait); then
			return 0;
		fi
	elif [ "$(whoami)" = "root" ]; then
		if (dpkg -i $* && wait); then
			return 0;
		fi
	else
		if (sudo dpkg -i $* && wait); then
			return 0
		fi
	fi
	errorcontrol "$item"
	return 1
}

function checkdepends {
	pkgdepends=$(dpkg-checkbuilddeps &> /dev/stdout | sed "s/ | [^ ]*//g;s/([^)]*)//g"|cut -f3 -d":")
	if [ -n "$pkgdepends" ]; then
		echo "You're missing the following dependencies, please install them: "
		for depend in $pkgdepends; do
			echo -n " $depend,"
		done
		echo ""
		echo "Would you like to install these missing packages?"
		if (askuser); then
			for depend in $pkgdepends; do
				for deb in $(find "../../$DEBDIR/" -maxdepth 1 -type f -name "*.deb" 2> /dev/null); do
					if [ "$(dpkg-deb --field $deb Package)" = "$depend" ]; then
						pkglist="$pkglist $deb"
					fi
				done
			done
			if [ -n "$pkglist" ]; then
				installpackages $pkglist
			fi
			if [ "$sudopwdset" = "true" ]; then
				if (echo "$sudopwd" | sudo -S apt-get -y install $pkgdepends && wait); then
					return 0
				fi
			elif [ "$(whoami)" = "root" ]; then
				if (apt-get install $pkgdepends -y && wait); then
					return 0;
				fi
			else
				if (sudo apt-get install $pkgdepends -y && wait); then
					return 0;
				fi
			fi
		fi
		echo "Would you like to skip this package and continue building?"
		if ! (askuser); then
			exit 2;
		else
			return 2;
		fi
	fi
	return 0;
}

function compversion {
	version=0
	file_ver=0
	configac_ver=0
	configin_ver=0
	debian_ver=0
	debian_ver_prefix="$(expr "$(dpkg-parsechangelog|grep --max-count=1 -F "Version:" |cut -d" " -f2)" : "\([0-9]\+\):.*")"

	if [ -f "./VERSION" ]; then
		. "./VERSION"
		file_ver="$VERSION"
		VERSION=""
	fi

# 	if [ -z "$base_comp_ver" ]; then
# 		if [ -n "$base_ver" ]; then
# 			base_comp_ver="$base_ver"
# 		else

	if [ -f "configure.ac" ]; then
		configac_ver="$(expr "$(cat configure.ac)" : ".*AC_INIT(\[[^]]*\][ ]*,[ ]*\[\([^]]*\)\][ ]*[^)]*).*")"
		if [ -z "$configac_ver" ]; then
			configac_major="$(expr "$(cat configure.ac)" : ".*m4_define(compiz_version_major,[ ]*\([0-9]\+\)).*")"
			configac_minor="$(expr "$(cat configure.ac)" : ".*m4_define(compiz_version_minor,[ ]*\([0-9]\+\)).*")"
			configac_micro="$(expr "$(cat configure.ac)" : ".*m4_define(compiz_version_micro,[ ]*\([0-9]\+\)).*")"
			if [ -n "$configac_major" ] && [ -n "$configac_minor" ]; then
				configac_ver="$configac_major.$configac_minor.$configac_micro"
			fi
		fi
	fi

	if [ -f "configure.in.in" ]; then
		configin_ver="$(expr "$(cat configure.in.in)" : ".*AM_INIT_AUTOMAKE([^,]*,\([^)]*\)).*")"
	fi

	debian_ver=$(dpkg-parsechangelog | grep --max-count=1 -F "Version:" | cut -d" " -f2)

	#sed "s/[0-9]\+://; s/[+~-][0-9]\+[a-z0-9]*//; s/[+~-][(git)(cvs)(svn)]\+[0-9]\+.*//")
# 	base_comp_ver=$(echo "$base_comp_ver" | sed 's/-svn//g;s/-git//g');

	for ver in $base_ver $file_ver $configac_ver $configin_ver $debian_ver; do
		ver=$(echo "$ver" | sed "s/^.\+://; s/\([0-9a-zA-Z.]\+\).*/\1/g")
		if (dpkg --compare-versions $ver gt $version); then
			version="$ver"
		fi
	done

	if [ -n "$debian_ver_prefix" ]; then
		version="$debian_ver_prefix:$version"
	fi

	build=0
	repack=1
	buildstamp=0
	tstpkg="$(cat debian/control |grep "^Package:" -m1| cut -d" " -f2)"

	# TODO: should be analyzed the first package found with same Source
	for oldpkg in $(find "../../$DEBDIR/" -maxdepth 1 -type f -name "${tstpkg}_*~git$(git_commit_date)+*.deb" 2> /dev/null); do
		pkgbuild="$(expr "$(dpkg-deb --field "$oldpkg" Version)" : ".\++${package_sufix}\([0-9]\+\).*")"
		if ( [ -n "$pkgbuild" ] && [ "$pkgbuild" -gt "$build" ] ); then
			build=$pkgbuild
		fi
		if ( [ $action = "rebuild" ] || [ $action = "build" ] ); then
			build=$(($build + 1))
			buildstamp="$build"
		elif [ $action = "repack" ]; then
			pkgpack="$(expr "$(dpkg-deb --field "$oldpkg" Version)" : ".\++${package_sufix}${build}.\([0-9]\+\)")"
			if ( [ -n "$pkgpack" ] && [ "$pkgpack" -ge "$repack" ] ); then
				repack=$(($pkgpack + 1))
			fi
			buildstamp="$build.$repack"
		fi
	done

	#".\++git[0-9]\{8\}-r\([0-9]\+\)~3v1ubuntu[0-9]\+" -> fusion-core_0.3+git20070401-r1~3v1ubuntu5

	debversion="${version}~git$(git_commit_date)+${package_sufix}${buildstamp}"
}

function buildpkg {
	rm -f ../*.deb

	if [ -n "$(echo $* | grep "repack")" ]; then
		action="repack"
	elif [ -n "$(echo $* | grep "rebuild")" ]; then
		action="rebuild"
	else
		action="build"
	fi

	source_package=$(dpkg-parsechangelog|grep --max-count=1 -F "Source:" |cut -d" " -f2)

	if [ -n "$(which lsb_release)" ]; then
		distro="$(lsb_release -c|cut -f2)"
	elif [ -f "/etc/lsb-release" ]; then
		distro="$(cat /etc/lsb-release|grep DISTRIB_CODENAME | cut -d'=' -f2)"
	fi

	if [ -z "$distro" ]; then
		distro="unstable";
	fi

	compversion

	echo -e "$source_package ($debversion) $distro; urgency=low\n\n  * Upgrade to GIT commit $(git_commit | sed "s/ /\n     - /g")\n\n -- $packager <$packager_email>  $(LC_ALL=en_US date +"%a, %d %b %Y %T %z")\n" > "./debian/changelog"
	sed "$(cat "../$DISTRODIR_ITEM/$item/debian/control" | grep "^Maintainer:" -n -m1 | cut -d':' -f1)cMaintainer: $packager <$packager_email>" "../$DISTRODIR_ITEM/$item/debian/control" > "./debian/control"
	cat "../$DISTRODIR_ITEM/$item/debian/changelog" >> "./debian/changelog"

# 	if ( [ -f "./VERSION" ] && [ ! -f "./VERSION.base" ] ); then
# 		mv -v "./VERSION" "./VERSION.base"
# 		cp -v "./VERSION.base" "./VERSION"
# 		perl -i -p -e "s/VERSION=.*/VERSION=$version/" "./VERSION"
# 	fi

	if [ $action = "repack" ]; then
		cmd2run="$repkg_cmd"
	else
		cmd2run="$buildpkg_cmd"
	fi

	if ! $cmd2run; then #fakeroot dh_gencontrol -u"-v$version"
		errorcontrol $item
		report="$report\nBUILD FAILED for $item"
		return 2
	fi

	if [ -f pkgxtra.sh ]; then
		# TODO if errors, ask to continue anyway!
		chmod +x pkgxtra.sh
		echo -e "\nRunning extra scripts for $item..."
		if ! ./pkgxtra.sh $action; then
			errorcontrol $item
			report="$report\nBUILD FAILED for extrascripts on $item"
			return 2
		fi
	fi

	for deb in $(find "../..$DEBDIR/" -maxdepth 1 -type f -name "*.deb" 2> /dev/null); do
		if  [ "$(dpkg-deb --field "$deb" Source)" = "$source_package" ]; then
			mv -f "$deb" "../../$DEBOLDDIR";
		fi
	done

	mv -f ../*$package_sufix*.deb "../../$DEBDIR/"
	mkdir -p "../../$DEBOLDDIR"
	mv -f ../*.changes "../../$CHANGEDIR" &> /dev/null

	unset deb
	for package in $(cat debian/control |grep Package| cut -d" " -f2); do
		for deb in $(find "../../$DEBDIR/" -maxdepth 1 -type f -name "${package}_*.deb" 2> /dev/null); do
			if  [ -z $(dpkg-deb --field "$deb" Version | grep -F "$debversion") ]; then
				mv -f "$deb" "../../$DEBOLDDIR";
			fi
		done
	done

	rm -rf ./debian

# 	if [ -f "./VERSION.base" ]; then
# 		mv -v "./VERSION.base" "./VERSION"
# 	fi
}

mkdir -p "../$CHANGEDIR" "../$DEBDIR"
#rm -f ../debs/*.deb

ITEMS="$PRIOPKGS"

for fusiondir in $DISTRODIR/* $DISTRODIR_USER/*; do
	if [ -n "$(echo $fusiondir | grep -F "$DISTRODIR_USER")" ]; then
		itemdir="${fusiondir/$DISTRODIR_USER\//}"
	else
		itemdir="${fusiondir/$DISTRODIR\//}"
	fi

	if ( [ -d $fusiondir ] &&
	     [ -d $fusiondir/debian ] &&
	     ( [ -f $itemdir/autogen.sh ] || [ -f $itemdir/setup.py ] )); then
		for userfusiondir in $commandline; do
			if ( [ "$userfusiondir" = "$itemdir" ] ); then
				USERITEMS="$USERITEMS $itemdir"
			fi
		done
		
		found="false"
		for item in $ITEMS; do
			if [ "$item" = "$itemdir" ]; then
				found="true"
			fi
		done
		
		if [ "$found" != "true" ]; then
			ITEMS="$ITEMS $itemdir";
		fi
	fi
done

if [ "$USERITEMS" != "" ]; then
	ITEMS="$USERITEMS"
fi

if [ "$INCLUDEDEBUG" = "true" ]; then
	export DEB_BUILD_OPTIONS="nostrip"
fi


for item in $ITEMS; do
	if ! cd $item; then
		report="$report\nCAN'T enter in $item directory"
		errorcontrol "$item"
	fi

	rm -rf ./debian

	if [ -d "../$DISTRODIR_USER/$item/debian" ]; then
		DISTRODIR_ITEM="$DISTRODIR_USER"
	elif [ -d "../$DISTRODIR/$item/debian" ]; then
		DISTRODIR_ITEM="$DISTRODIR"
	else
		report="$report\nNo debian files for $item"
		errorcontrol "$item"
	fi
	#ln -sf ../$DISTRODIR/$item/debian
	cp -ar ../$DISTRODIR_ITEM/$item/debian ./

	git_ignore_add ".build-done" ".abi-done" "pkgxtra.sh"

	if [ ! -e ./.build-done ]; then
		echo 0 > "./.build-done";
	fi

	latest_ver="$(cat ./.build-done)"

	if find . \( -iname "*.c*" -o -iname "*.h*" \) -print | xargs grep -q -m1 'checkPluginABI[ \t]*([ \t]*"core"[ \t]*,[ \t]*CORE_ABIVERSION[ \t]*)' &> /dev/null; then
		if [ ! -e ./.abi-done ]; then
			echo 0 > "./.abi-done";
		fi
		local_abi="$(cat ./.abi-done)"
	else
		unset local_abi
	fi

	rm -f "./debian/stamp-patched"
	if [ -d ".pc" ]; then
		if ! (git-diff-files -p | patch -Rp1 &> /dev/null); then
			errorcontrol "$item"
		fi
		rm -rf ".pc"
	fi

	if [ -n "$(echo $commandline | grep -w "nopatch")" ]; then
		if [ -f "./debian/patches/series" ]; then
			echo '' > "./debian/patches/series"
			if ! (git-diff-files -p | patch -Rp1 &> /dev/null); then
				errorcontrol "$item"
			fi
		fi
	fi

	if [ "$(git_commit)" != "$latest_ver" ]; then
		echo -e "\nBuilding $item..."
		if (checkdepends); then
			if $patch_cmd; $autogenpkg_cmd; buildpkg; then
				report="$report\n$item built OK"
				case "$item" in
					bcop)
					 installpackages "../../$DEBDIR/"compiz-bcop_*.deb;;
					compiz)
					 installpackages "../../$DEBDIR/"{libdecoration,compiz-dev_}*.deb ;;
					libcompizconfig)
					 installpackages "../../$DEBDIR/"libcompizconfig0*.deb;;
					plugins-main)
					 installpackages "../../$DEBDIR/"compiz-fusion-plugins-main_*.deb ;;
				esac
				echo "$(git_commit)" > ./.build-done
				if [ -n "$local_abi" ]; then
					echo "$(abi_version)" > ./.abi-done
				fi
			else
				report="$report\nBUILD FAILED for $item"
				wait
				errorcontrol "$item"
			fi
		else
			report="$report\nMISSING DEPENDENCIES for $item"
		fi
	else #elif [ "$(git_commit)" = "$latest_ver" ]; then
		if ( [ -n "$(echo $commandline | grep "rebuild")" ] ||
		   ( [ -n "$local_abi" ] && [ "$(abi_version)" != "$local_abi" ] ) ||
		   [ -f "./.rebuild" ] ); then #||
# 		   ( [ "$DISTRODIR_ITEM" = "$DISTRODIR" ] ) &&
# 		   [ "$(cd ../$DISTRODIR_ITEM && git_commit_date)" -gt "$(git_commit_date)" ] ); then
			echo -e "\nRebuilding $item..."
			if (checkdepends); then
				if $patch_cmd; make clean; buildpkg rebuild; then # && make clean ?
					echo "$(abi_version)" > ./.abi-done
					rm -f "./.rebuild"
					report="$report\n$item rebuilt OK"
				else
					report="$report\nREBUILD FAILED for $item"
					errorcontrol "$item"
				fi
			else
				report="$report\nMISSING DEPENDENCIES for $item"
			fi
		elif ( [ -n "$(echo $commandline | grep "repack")" ] || [ -f "./.repack" ] ); then
			echo -e "\nRepacking $item..."
			rm -f "./.repack"
			if (checkdepends); then
				$patch_cmd; buildpkg repack;
				report="$report\n$item repackaged OK"
			else
				report="$report\nMISSING DEPENDENCIES for $item"
			fi
		else
			report="$report\n$item already built"
		fi
	fi
	cd ../
done

echo -e "\n$report\n";
